﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Singleton;
using IntroduceCompany.Util;
using System.IO;
using IntroduceCompany.Models;

namespace IntroduceCompany.Controllers
{
    [HandleError]
    [CheckModule(ConstantClass.Backend_Article_MenuID)]
    public class ArticleController : BaseController
    {
     
    #region BackEnd_Article

        [Authorize(Roles = ConstantClass.autArticle)]
        public ActionResult ArticleList()
        {
            string languageID = ConstantClass.markViewAllLanguage;
            if (Request.Cookies[ConstantClass.cooLanguage] != null && Request.Cookies[ConstantClass.cooLanguage].Value != "")
            {
                languageID = Request.Cookies[ConstantClass.cooLanguage].Value;
            }

            string articleTypeID = "";
            if (Request.Cookies[ConstantClass.cooArticleTypeID] != null && Request.Cookies[ConstantClass.cooArticleTypeID].Value != "")
            {
                articleTypeID = Request.Cookies[ConstantClass.cooArticleTypeID].Value;
            }

            string amount = ConstantClass.defaultAmount;
            if (Request.Cookies[ConstantClass.cooAmount] != null )
            {
                amount = Request.Cookies[ConstantClass.cooAmount].Value;
            }

            ViewData["amountList"] = new SelectList(new[] { "10", "25", "50", "100", "250" }
                .Select(x => new { value = x, text = x }),
                "value", "text", amount);

            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);
            ViewData["ArticleTypeList"] = new SelectList(DataSingleton.GetArticleModels().GetArticleType(languageID).ToList(), "MenuListID", "MenuName", articleTypeID);

            return View("/Views/Backend/Article/ArticleList.aspx", DataSingleton.GetArticleModels().GetAllArticle(languageID, articleTypeID, amount));
            //return View("/Views/Backend/Article/ArticleList.aspx", DataSingleton.GetArticleModels().GetAllArticle(languageID, articleTypeID));
        }

        /// <summary>
        /// Change Article Status that is visible or invisible
        /// </summary>
        /// <param name="menuListID"></param>
        /// <param name="menuVisible"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autArticle)]
        public ActionResult ChangeArticleVisible(int articleID, bool articleVisible)
        {
            if (ModelState.IsValid)
            {
                DataSingleton.GetArticleModels().ChangeArticleVisible(articleID, articleVisible);
            }
            return RedirectToAction("ArticleList", "Article");
        }

        [Authorize(Roles = ConstantClass.autArticle)]
        [ValidateInput(false)]
        [ActionName("Edit")]
        public ActionResult ArticleEdit(int articleID,String languageID, int articleTypeID)
        {
            ViewData["ArticleTypeList"] = new SelectList(DataSingleton.GetMenuListModels().GetArticleType(languageID).ToList(), "MenuListID", "MenuName", articleTypeID);
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", ConstantClass.mainLanguageID);//languageID
          //  Session["ArticleLanguage"] = "true";//khởi tạo giá trị cho session, đề dùng hàm bên dưới;
            ArticleListView oneArticleView = DataSingleton.GetArticleModels().GetArticleByArticleIDAndLanguageID(articleID, languageID);
            
            if (oneArticleView == null)
            {
                oneArticleView = new ArticleListView();
                Article article = DataSingleton.GetArticleModels().GetArticleByArticleID(articleID);

                oneArticleView.ArticleID = article.ArticleID;
                oneArticleView.ArticleTypeID = article.ArticleTypeID;
                oneArticleView.Photo = article.Photo;

                oneArticleView.ArticleVisible = article.ArticleVisible;
                oneArticleView.ArticleDate = article.ArticleDate;
                oneArticleView.Username = article.UserName;
           
               // Session["ArticleLanguage"] = "false";
            }
            return View("/Views/Backend/Article/ArticleEdit.aspx", oneArticleView);
        }

        [Authorize(Roles = ConstantClass.autArticle)]
        [HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ArticleEdit(ArticleListView _NewOneArticleView, HttpPostedFileBase uploadFile)
        {
            string username = HttpContext.User.Identity.Name;
            _NewOneArticleView.Username = username;
            if (uploadFile != null && uploadFile.ContentLength > 0)
            {
                //Upload Image article
                _NewOneArticleView.Photo = DataSingleton.GetGeneralModels().UploadImage(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString(),
                    "Image/Article/thumbnail/"), _NewOneArticleView.Photo, _NewOneArticleView.Title, ConstantClass._articleThumbnailHeight);
                DataSingleton.GetArticleModels().UpdateArticleThumbnail(_NewOneArticleView);
            }
            ArticleListView oneArticleView = DataSingleton.GetArticleModels().GetArticleByArticleIDAndLanguageID(_NewOneArticleView.ArticleID, _NewOneArticleView.LanguageID);

            if (oneArticleView != null)// the article has this language so update only
            {
                if (ModelState.IsValid && DataSingleton.GetArticleModels().ArticleEdit(_NewOneArticleView))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("Notice", "Thông tin đã được cập nhật.");
                }
                else
                {
                    ModelState.AddModelError("Notice", "Có lỗi khi cập nhật thông tin.");
                }
            }
            else // the article do not has this language so insert new language
            {
                if (ModelState.IsValid && DataSingleton.GetArticleModels().Article_L_Create(_NewOneArticleView))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("Notice", "Bài viết đã được cập nhật thêm ngôn ngữ mới.");
                }
                else
                {
                   // Session["ArticleLanguage"] = "false";
                    ModelState.AddModelError("Notice", "Có lỗi khi cập nhật thêm ngôn mới.");
                }
            }
            ViewData["ArticleTypeList"] = new SelectList(DataSingleton.GetMenuListModels().GetArticleType(_NewOneArticleView.LanguageID).ToList(),
                "MenuListID", "MenuName", _NewOneArticleView.LanguageID);
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName",
                _NewOneArticleView.LanguageID);

            _NewOneArticleView.ArticleDate = DateTime.Now;
            _NewOneArticleView.FullName = DataSingleton.GetInstance().Administrators.SingleOrDefault(u => u.UserName == username).FullName;

            return View("/Views/Backend/Article/ArticleEdit.aspx", _NewOneArticleView);
           
        }

        [Authorize(Roles = ConstantClass.autArticle)]
        public ActionResult ArticleDelete(int articleID)
        {
            DataSingleton.GetArticleModels().ArticleDelete(articleID, Path.Combine(Request.PhysicalApplicationPath.ToString() , "Image/Article/thumbnail"));
            return RedirectToAction("ArticleList", "Article");
        }

        [Authorize(Roles = ConstantClass.autArticle)]
        public ActionResult ChangeArticleType(String articleTypeID)
        {
            if (Request.Cookies[ConstantClass.cooArticleTypeID] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooArticleTypeID, articleTypeID);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddHours(2);
            }
            else
            {
                Response.Cookies[ConstantClass.cooArticleTypeID].Value = articleTypeID;
            }

            return RedirectToAction("ArticleList", "Article");
        }

        /// <summary>
        /// in backend, get a specific amount of articles
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autArticle)]
        public ActionResult ChangeAmountToShow(String amountList)
        {
            if (Request.Cookies[ConstantClass.cooAmount] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooAmount, amountList);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddHours(1);
            }
            else
            {
                Response.Cookies[ConstantClass.cooAmount].Value = amountList;
            }

            return RedirectToAction("ArticleList", "Article");
        }

        [Authorize(Roles = ConstantClass.autArticle)]
        public ActionResult ArticleCreate()
        {
            string articleTypeID = "";
            if (Request.Cookies[ConstantClass.cooArticleTypeID] != null && Request.Cookies[ConstantClass.cooArticleTypeID].Value != "")
            {
                articleTypeID = Request.Cookies[ConstantClass.cooArticleTypeID].Value;
            }
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");
            ViewData["ArticleTypeList"] = new SelectList(DataSingleton.GetArticleModels().GetArticleType(ConstantClass.markViewAllLanguage).ToList(), "MenuListID", "MenuName");
            return View("/Views/Backend/Article/ArticleCreate.aspx");
        }

        [Authorize(Roles = ConstantClass.autArticle)]
        [HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ArticleCreate(ArticleListView _NewOneArticleView, HttpPostedFileBase uploadFile)
        {
           // int articleMaxID = 0;
            string newImageName = "";
            if (uploadFile != null && uploadFile.ContentLength > 0 && _NewOneArticleView.Title != null && _NewOneArticleView.Title.ToString() !="")
            {
                //Upload Image article
                newImageName = DataSingleton.GetGeneralModels().UploadImage(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString()
                    , "Image/Article/thumbnail/"), _NewOneArticleView.Photo, _NewOneArticleView.Title, ConstantClass._articleThumbnailHeight);

                _NewOneArticleView.Photo = newImageName;
            }
            _NewOneArticleView.Username = HttpContext.User.Identity.Name;// thay khi thực hiện chức năng log in
            string articleTypeID = "";
            if (Request.Cookies[ConstantClass.cooArticleTypeID] != null && Request.Cookies[ConstantClass.cooArticleTypeID].Value != "")
            {
                articleTypeID = Request.Cookies[ConstantClass.cooArticleTypeID].Value;
            }

            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");
            ViewData["ArticleTypeList"] = new SelectList(DataSingleton.GetArticleModels().GetArticleType(ConstantClass.markViewAllLanguage).ToList(), "MenuListID", "MenuName");

            if (ModelState.IsValid)
            {
                _NewOneArticleView.ArticleID = DataSingleton.GetArticleModels().ArticleCreate(_NewOneArticleView);
                DataSingleton.GetArticleModels().Article_L_Create(_NewOneArticleView);

                return RedirectToAction("Edit", "Article", new
                {
                    articleID = _NewOneArticleView.ArticleID,
                    languageID = _NewOneArticleView.LanguageID
                    ,
                    articleTypeID = _NewOneArticleView.ArticleTypeID
                });

            }
            else{
               return View("/Views/Backend/Article/ArticleCreate.aspx");
            }
        }

    #endregion

///////////////////////////////////////////////////////////////////////////

    #region FrontEnd_Article

        public ActionResult Frontend_ArticleList(String articleTypeSEO_URL, String pageIndex)
        {
           // string articleTypeID = DataSingleton.GetArticleModels().GetArticleTypeIDBySEO_URL(articleTypeSEO_URL);
            int articleTypeID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(articleTypeSEO_URL);
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
          //  ViewData["SiteMapPathUserControl"] = DataSingleton.GetMenuListModels().BuildSiteMapPath(articleTypeID, languageID);
            if (articleTypeID != 0)
            {
                bool article_single_check = DataSingleton.GetArticleModels().CheckArticleSingle(articleTypeID);
                if (article_single_check)
                {
                    ViewData["Article_Single_Check"] = "true";
                    ArticleListView article_temp = DataSingleton.GetArticleModels().Frontend_GetLatestArticles(articleTypeID, languageID);
                    if (article_temp == null)
                    {
                        article_temp = new ArticleListView();
                        article_temp.Title = "Không có bài viết ngôn ngữ này";
                    }
                    ViewData["Latest_Article"] = article_temp;
                }
                else
                {
                    ViewData["Article_Single_Check"] = "false";
                    ViewData["articleTypeID_Temp"] = articleTypeID;// để truyền articleTypeID dến Func Frontend_ArticleList_Middle(partial view) thông wa trang ArticeList.aspx
                    ViewData["pageIndex"] = pageIndex;// để truyền pageIndex("1","2","3",...) dến Func Frontend_ArticleList_Middle(partial view) thông wa trang ArticeList.aspx
                }
                return View("/Views/Frontend/Article/ArticleList.aspx");
            }
            else
            {
                ViewData["Article_Single_Check"] = null;
                ViewData["articleTypeID_Temp"] = null;// để truyền articleTypeID dến Func Frontend_ArticleList_Middle(partial view) thông wa trang ArticeList.aspx
                ViewData["pageIndex"] = null;

                return View("/Views/Frontend/Article/ArticleList.aspx");
            }
        }

        [ChildActionOnly]
        public ActionResult Frontend_ArticleList_Middle(String articleTypeID, String pageIndex)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();

      ////////////////////////// start paging
            int totalRows = DataSingleton.GetArticleModels().Frontend_GetTotalRowsOneTypeOneLanguage(articleTypeID, languageID);
            int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.ArticlePageStep);

            if (pageIndex != "1")
            {
                ViewData["Previous_Mark_Visibility"] = "true";
            }
            if (totalPages != Convert.ToInt16(pageIndex))
            {
                ViewData["Next_Mark_Visibility"] = "true";
            }

            ViewData["NextPageIndex"] = (Convert.ToInt16(pageIndex) + 1).ToString();
            ViewData["PreviousPageIndex"] = (Convert.ToInt16(pageIndex) - 1).ToString();
      ////////////////////////// end paging

            ViewData["articleTypeID_Temp"] = articleTypeID;// dùng bên trang giao dien Middle.ascx
            return View("/Views/Frontend/Article/Middle.ascx", DataSingleton.GetArticleModels().Frontend_GetOnePageArticle(languageID, articleTypeID, pageIndex
                , ConstantClass.ArticlePageStep));
        }

        public ActionResult Frontend_ArticleDetails(String articleSEO_URL)
        {
            int articleID = DataSingleton.GetArticleModels().GetArticleIDBy_SEO_URL(articleSEO_URL);
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            ArticleListView temp;
            if (articleID != 0)
            {
                int articleTypeID = DataSingleton.GetArticleModels().GetArticleByArticleID(articleID).ArticleTypeID;
                temp = DataSingleton.GetArticleModels().Frontend_GetArticleByArticleIDAndLanguageID(articleID, languageID);
                ViewData["Article_Avaibility"] = "true";
            }
            else
            {
                temp = new ArticleListView();
                ViewData["Article_Avaibility"] = "false";
            }
            return View("/Views/Frontend/Article/ArticleDetails.aspx", temp);
        }

        /// <summary>
        /// use in backend , articleList but link to frontend for admin to check quickly and convenient
        /// </summary>
        /// <param name="articleSEO_URL"></param>
        /// <returns></returns>
        public ActionResult Frontend_ArticleDetails2(int articleID,String languageID ,int articleTypeID )
        {
            string url = "/" + languageID + "/artDe/";
            string articleType_SEO_URL = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(articleTypeID.ToString(), languageID);
            string article_SEO_URL = DataSingleton.GetArticleModels().GetArticle_SEO_URL_By_ArticleID_LanguageID(articleID, languageID);
            url += articleType_SEO_URL + "/" + article_SEO_URL;
            return Redirect(url);
        }

     #endregion


    }
}
